//
//  ZCollectionViewController.m
//  LoopImage
//
//  Created by 周成龙 on 2018/3/7.
//  Copyright © 2018年 XZL. All rights reserved.
//

#import "ZCollectionViewController.h"

#import "PhotoCell.h"
#import "FlowLayout.h"

@interface ZCollectionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
{
    NSArray <NSString *>*_urls;
}
@property (nonatomic, strong) UICollectionView *collectionView;

@end
static NSString * const ID = @"cell";
@implementation ZCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSMutableArray *arr = @[].mutableCopy;
    for (NSInteger i = 0 ; i < 9; i ++) {
        NSString *imageName = [NSString stringWithFormat:@"%02ld.jpg", i + 1];
        [arr addObject:imageName];
    }
    _urls = arr.copy;
    
    // 添加collectionView
    [self addCollectionView];
}

- (void)addCollectionView
{
    // 创建流水布局
    FlowLayout *flowLayout = [[FlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake(180, 180);
    CGFloat margin = (self.view.bounds.size.width - 180) * 0.5;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 200) collectionViewLayout:flowLayout];
    
    collectionView.backgroundColor = [UIColor greenColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.view addSubview:collectionView];
    
    [collectionView registerNib:[UINib nibWithNibName:@"PhotoCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_urls count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
    
    NSString *imageName = _urls[indexPath.item];
    cell.image = [UIImage imageNamed:imageName];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"--%zd", indexPath.row);
}

@end
